import requests
"""
- 通过ip请求淘宝的一个接口获取到省份和运营商
- 接口：https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=要查询的ip地址
- 每一行变成这种形式保存到文件
- 格式：ip,中国,湖南,电信
{
    "data": {
        "area": "",
        "country": "中国",
        "isp_id": "100017",
        "queryIp": "222.244.201.2",
        "city": "长沙",
        "ip": "222.244.201.2",
        "isp": "电信",
        "county": "",
        "region_id": "430000",
        "area_id": "",
        "county_id": null,
        "region": "湖南",
        "country_id": "CN",
        "city_id": "430100"
    },
    "msg": "query success",
    "code": 0
}
"""


def get_ipinfo(ip):
    try:
        path = f"https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip={ip}"
        status = requests.get(path)
        data_dict = status.json()  # 将json解析成字典
        # print(type(data_dict),data_dict)
        if data_dict["code"] == 0:
            ipinfo = data_dict["data"]
            ips = ipinfo["ip"]
            country = ipinfo["country"]
            region = ipinfo["region"]
            isp = ipinfo["isp"]
            return ips, country, region, isp
    except Exception:
        print("解析失败了，再试一次~~~~~~~~~")


# print(get_ipinfo("222.244.201.2"))
# 122.165.23.3
fp = open("ipinfo.txt", "a", encoding="utf-8")
while True:
    try:
        ins = input("请输入你的IP地址（按q退出）：")
        if ins == "q":
            print("程序退出")
            break
        fip, fcountry, fregion, fisp = get_ipinfo(ins)
        print(fip, fcountry, fregion, fisp)
        # 写入文件
        fp.write(f"{fip},{fcountry},{fregion},{fisp}\n")
        print("数据写入成功~~~~~")
    except Exception:
        print("获取信息失败了，再试一次~~~~~~~~~")
fp.close()

